<template>
  <div>
    <div class="mindMap" :id="id" :style="{height: height}"></div>
  </div>
</template>

<script lang="ts">
import {defineComponent, onMounted, watch, ref, nextTick, onBeforeUnmount} from 'vue';
import MindElixir from 'mind-elixir'
import {uploadAttachment} from "/@/api/system/common";

export default defineComponent({
  name: 'MindElixir',
  props: {
    id: {
      type: String,
      default() {
        return "mindMap"
      }
    },
    height: {
      type: String,
      default() {
        return "calc(100vh - 170px)"
      }
    },
    nodes: {
      type: Object,
      default() {
        return null
      }
    }
  },
  setup(props, {emit}) {
    const mind = ref(null)
    onMounted(() => {
      nextTick(() => {
        initMindMap();
      });
    });
    watch(() => props.nodes, (newVal) => {
      if(newVal?.hasOwnProperty('nodeData')) {
        mind.value.refresh(newVal)
      } else {
        mind.value.refresh(MindElixir.new('new topic'))
      }
    })
    const initMindMap = () => {
      mind.value = new MindElixir({
        el: "#" + props.id, // or HTMLDivElement
        direction: MindElixir.SIDE,
        draggable: true, // default true
        contextMenu: true, // default true
        toolBar: true, // default true
        nodeMenu: true, // default true
        keypress: true, // default true
        locale: 'zh_CN', // [zh_CN,zh_TW,en,ja,pt,ru] waiting for PRs
        overflowHidden: false, // default false
        // mainLinkStyle: 2, // [1,2] default 1
        mouseSelectionButton: 0, // 0 for left button, 2 for right button, default 0
        contextMenuOption: {
          focus: true,
          link: true,
          extend: [
            {
              name: 'Node edit',
              onclick: () => {
                alert('extend menu')
              },
            },
          ],
        },
        before: {
          insertSibling(el, obj) {
            return true
          },
          async addChild(el, obj) {
            // await sleep()
            return true
          },
        },
      })
      mind.value.init(MindElixir.new('new topic'))
      if (props.nodes?.hasOwnProperty('nodeData')) {
        mind.value.refresh(props.nodes)
      }
    }
    const getMindMapData = () => {
      return mind.value.getDataString()
    }
    const refreshMindMapData = (data: object) => {
      return mind.value.refresh(data)
    }
    const exportAsPicture = async (type: string) => {
      try {
        let blob = null
        // if (type === 'png') blob = await mind.value.exportPng(false, style + katex)
        if (type === 'png') blob = await mind.value.exportPng(false)
        // else blob = await mind.value.exportSvg(false, style + katex)
        else blob = await mind.value.exportSvg(false)
        if (!blob) return
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = 'filename.' + type
        a.click()
        URL.revokeObjectURL(url)
      } catch (e) {
        console.error(e)
      }
    }
    const uploadPicture = async (type: string) => {
      try {
        let blob = null
        // if (type === 'png') blob = await mind.value.exportPng(false, style + katex)
        if (type === 'png') blob = await mind.value.exportPng(false)
        // else blob = await mind.value.exportSvg(false, style + katex)
        else blob = await mind.value.exportSvg(false)
        if (!blob) return

        const formData = new FormData();
        formData.append('file', blob, 'mindmap_preview.' + type); // 附加 Blob 到表单数据
        let _return = ''
        await uploadAttachment(formData).then(res => {
          _return = res.data.url;
        })
        return _return
      } catch (e) {
        console.error(e)
      }
    }
    onBeforeUnmount(() => {
      mind.value = null
    })
    return {
      getMindMapData,
      exportAsPicture,
      uploadPicture,
      refreshMindMapData,
    }
  }
});
</script>

<style scoped lang="scss">
.mindMap {
  width: 100%;
}
</style>
